package com.mxnet.chongjin.supoman.activity;

import android.app.Instrumentation;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;

import com.mxnet.chongjin.supoman.R;
import com.mxnet.chongjin.supoman.adapter.LvPartAdapter;
import com.mxnet.chongjin.supoman.bean.Part;
import com.mxnet.chongjin.supoman.config.Api;
import com.mxnet.chongjin.supoman.style.ListViewForScrollView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

public class PartsActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
    private Context mContext;
    private LinearLayout mLinearLayout;
    private Button mButton;
    private ListViewForScrollView mLvType1, mLvType2;
    private ScrollView mScrollView;
    private List<Part> mList1, mList2;
    private LvPartAdapter mAdapter1, mAdapter2;
    private int fromTag;
    private String mPartList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_parts);
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        getWindow().setStatusBarColor(Color.TRANSPARENT);
        mContext = PartsActivity.this;

        initView();
        initData();
    }

    public void initView() {
        mLinearLayout = findViewById(R.id.ll_parts);
        mLinearLayout.setOnClickListener(this);

        mButton = findViewById(R.id.btn_online_repair);
        mButton.setOnClickListener(this);

        mLvType1 = findViewById(R.id.lv_parts_type1);
        mLvType1.setOnItemClickListener(this);

        mLvType2 = findViewById(R.id.lv_parts_type2);
        mLvType2.setOnItemClickListener(this);

        mScrollView = findViewById(R.id.sv_parts);
        mScrollView.smoothScrollTo(0, 0);
    }

    public void initData() {
        mList1 = new ArrayList<>();
        mList2 = new ArrayList<>();
        mPartList = "";
        fromTag = getIntent().getIntExtra("fromTag", 0);
        OkHttpUtils.get()
                .url(Api.URL_HEADER + Api.GET_PARTS + "data={" + "typeCodes:[\"006\",\"007\",\"008\",\"009\"]" + "}")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        if (!TextUtils.isEmpty(response)) {
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                boolean isSuccess = jsonObject.optBoolean("success");
                                if (isSuccess) {
                                    JSONObject data = jsonObject.optJSONObject("data");
                                    JSONArray list6 = data.optJSONArray("006");
                                    JSONArray list7 = data.optJSONArray("007");
                                    JSONArray list8 = data.optJSONArray("008");
                                    JSONArray list9 = data.optJSONArray("009");
                                    if (getResources().getConfiguration().locale.getCountry().equals("CN")) {
                                        for (int i = 0; i < list6.length(); i++) {
                                            JSONObject object = list6.optJSONObject(i);
                                            Part part = new Part();
                                            part.setId(object.optString("id"));
                                            part.setParamCode(object.optString("paramCode"));
                                            part.setParamName(object.optString("paramName"));
                                            part.setSeq(object.optInt("seq"));
                                            part.setTypeCode(object.optString("typeCode"));
                                            part.setTypeId(object.optString("typeId"));
                                            part.setTypeName(object.optString("typeName"));
                                            part.setSelected(false);
                                            mList1.add(part);
                                        }
                                        for (int j = 0; j < list7.length(); j++) {
                                            JSONObject object = list7.optJSONObject(j);
                                            Part part = new Part();
                                            part.setId(object.optString("id"));
                                            part.setParamCode(object.optString("paramCode"));
                                            part.setParamName(object.optString("paramName"));
                                            part.setSeq(object.optInt("seq"));
                                            part.setTypeCode(object.optString("typeCode"));
                                            part.setTypeId(object.optString("typeId"));
                                            part.setTypeName(object.optString("typeName"));
                                            part.setSelected(false);
                                            mList2.add(part);
                                        }
                                    } else {
                                        for (int i = 0; i < list8.length(); i++) {
                                            JSONObject object = list8.optJSONObject(i);
                                            Part part = new Part();
                                            part.setId(object.optString("id"));
                                            part.setParamCode(object.optString("paramCode"));
                                            part.setParamName(object.optString("paramName"));
                                            part.setSeq(object.optInt("seq"));
                                            part.setTypeCode(object.optString("typeCode"));
                                            part.setTypeId(object.optString("typeId"));
                                            part.setTypeName(object.optString("typeName"));
                                            part.setSelected(false);
                                            mList1.add(part);
                                        }
                                        for (int j = 0; j < list9.length(); j++) {
                                            JSONObject object = list9.optJSONObject(j);
                                            Part part = new Part();
                                            part.setId(object.optString("id"));
                                            part.setParamCode(object.optString("paramCode"));
                                            part.setParamName(object.optString("paramName"));
                                            part.setSeq(object.optInt("seq"));
                                            part.setTypeCode(object.optString("typeCode"));
                                            part.setTypeId(object.optString("typeId"));
                                            part.setTypeName(object.optString("typeName"));
                                            part.setSelected(false);
                                            mList2.add(part);
                                        }
                                    }
                                    mAdapter1 = new LvPartAdapter(mContext, mList1);
                                    mLvType1.setAdapter(mAdapter1);
                                    mAdapter2 = new LvPartAdapter(mContext, mList2);
                                    mLvType2.setAdapter(mAdapter2);
//                                    setDynamicHeight(mLvType1);
//                                    setDynamicHeight(mLvType2);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_parts:
                new Thread() {
                    public void run() {
                        try {
                            Instrumentation inst = new Instrumentation();
                            inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
                break;
            case R.id.btn_online_repair:
                for (Part p : mList1) {
                    if (p.isSelected()) {
                        mPartList += (p.getParamName() + ",");
                    }
                }
                for (Part p : mList2) {
                    if (p.isSelected()) {
                        mPartList += (p.getParamName() + ",");
                    }
                }
                Intent intent = new Intent();
                intent.putExtra("parts", mPartList.substring(0, mPartList.length() - 1));
                if (fromTag == 1001) {
                    PartsActivity.this.setResult(1002, intent);
                } else if (fromTag == 1003) {
                    setResult(1004, intent);
                }
                finish();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    public static void setDynamicHeight(ListView mListView) {
        LvPartAdapter mListAdapter = (LvPartAdapter) mListView.getAdapter();
        if (mListAdapter == null) {
            // when adapter is null
            return;
        }
        int height = 0;
        int desiredWidth = View.MeasureSpec.makeMeasureSpec(mListView.getWidth(), View.MeasureSpec.UNSPECIFIED);
        for (int i = 0; i < mListAdapter.getCount(); i++) {
            View listItem = mListAdapter.getView(i, null, mListView);
//            listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
            listItem.measure(0, 0);
            height += (listItem.getMeasuredHeight() + 2);
        }
        ViewGroup.LayoutParams params = mListView.getLayoutParams();
        params.height = height + (mListView.getDividerHeight() * (mListAdapter.getCount() - 1));
        mListView.setLayoutParams(params);
        mListView.requestLayout();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        ImageView imageView = view.findViewById(R.id.iv_item_parts);
        if (imageView.getVisibility() == View.INVISIBLE) {
            imageView.setVisibility(View.VISIBLE);
            ((Part) ((LvPartAdapter) parent.getAdapter()).getItem(position)).setSelected(true);
        } else {
            imageView.setVisibility(View.INVISIBLE);
            ((Part) ((LvPartAdapter) parent.getAdapter()).getItem(position)).setSelected(false);
        }
    }
}
